<?php
/*  Mysql操作类  */
class MySql {
    private $queryCount = 0;
    private $conn;
    private $result;
    private static $instance = null;
    private function __construct() {
        if (!function_exists('mysqli_connect')) {
            exit('服务器空间PHP不支持MySql数据库');
        }
        if (!$this->conn = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWD)) {
            switch ($this->geterrno()) {
                case 2005:
                    exit("连接数据库失败，数据库地址错误或者数据库服务器不可用");
                    break;
                case 2003:
                    exit("连接数据库失败，数据库端口错误");
                    break;
                case 2006:
                    exit("连接数据库失败，数据库服务器不可用");
                    break;
                case 1045:
                    exit("连接数据库失败，数据库用户名或密码错误");
                    break;
                default :
                    exit("连接数据库失败，请检查数据库信息。错误编号：" . $this->geterrno());
                    break;
            }
        }
        if ($this->getMysqlVersion() > '4.1') {
            mysqli_query($this->conn, "SET NAMES 'utf8'");
        }
        @mysqli_select_db($this->conn, DB_NAME) OR exit("连接数据库失败，未找到您填写的数据库");
    }

    public static function getInstance() {
        if (self::$instance == null) {
            self::$instance = new MySql();
        }
        return self::$instance;
    }

    function close() {
        return mysqli_close($this->conn);
    }

    function query($sql, $ignore_err = FALSE) {
        $this->result = @mysqli_query($this->conn, $sql , MysqLI_USE_RESULT);
        $this->queryCount++;
        if (!$ignore_err && !$this->result) {
            exit("SQL语句执行错误：$sql <br />" . $this->geterror());
        } else {
            return $this->result;
        }
    }

    function fetch_array($query, $type = MYSQLI_ASSOC) {
        return mysqli_fetch_array($query, $type);
    }

    function once_fetch_array($sql) {
        $this->result = $this->query($sql);
        return $this->fetch_array($this->result);
    }

    function fetch_row($query) {
        return mysqli_fetch_row($query);
    }

    function num_rows($query) {
        return mysqli_num_rows($query);
    }

    function num_fields($query) {
        return mysqli_num_fields($query);
    }

    function insert_id() {
        return mysqli_insert_id($this->conn);
    }

    function geterror() {
        return mysqli_error($this->conn);
    }

    function geterrno() {
        return mysqli_errno($this->conn);
    }

    function affected_rows() {
        return mysqli_affected_rows($this->conn);
    }

    function getMysqlVersion() {
        return mysqli_get_server_info($this->conn);
    }

    function getQueryCount() {
        return $this->queryCount;
    }

    function escape_string($sql) {
        return mysqli_real_escape_string($this->conn, $sql);
    }
}

?>